<?php

namespace app\http\middleware;

use app\common\Status;
use app\common\CacheKey;

class Defense
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     */
    public function handle($request, \Closure $next)
    {
        $ip = get_client_ip();
        if(!$ip){
            return $next($request);
        }
        $ip_arr = explode('.',$ip);
        $ip = $ip_arr[0].'.'.$ip_arr[1].'.'.$ip_arr[2];
        //查询ip是否被封禁
        $lock_ip = redis()->get(CacheKey::LOCK_REQUEST_IP.$ip);
        if($lock_ip){
            return returnJson(Status::IS_CC,lang('is_cc'));
        }
        //设置监控变量
        $cur_time = time();
        $refresh = '300'; //刷新次数
        $ip_data = redis()->get(CacheKey::REQUEST_IP.$ip);
        if($ip_data){
            $ip_data = json_decode($ip_data,true);
            if($ip_data['refresh_times'] > $refresh){
                //封禁
                redis()->set(CacheKey::LOCK_REQUEST_IP . $ip, $ip);
                redis()->expire(CacheKey::LOCK_REQUEST_IP . $ip, 3600);
                return returnJson(Status::IS_CC,lang('is_cc'));
            }else {
                $ip_data['refresh_times'] += 1;
                redis()->set(CacheKey::REQUEST_IP . $ip, json_encode($ip_data));
                redis()->expire(CacheKey::REQUEST_IP . $ip, 60 - (time()-$ip_data['last_time']));
            }
        }else{
            $data = [];
            $data['refresh_times'] = 1;
            $data['last_time'] = $cur_time;
            redis()->set(CacheKey::REQUEST_IP.$ip,json_encode($data));
            redis()->expire(CacheKey::REQUEST_IP.$ip,60);
        }
        return $next($request);
    }
}